<?php
/**
 * Created by lzl
 * Date: 2021 2021/10/18
 * Time: 14:04
 */
namespace App\Plugins\Forms;


use App\Models\ShareFreeGood;
use App\Models\ShareFreeLog;
use App\Models\ShareFreeOrder;

class ShareFreeOrderForms extends BaseForms
{

    /**
     * 生成|查询订单信息
     * @param $validated
     * @return ShareFreeOrder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrCreateOrder($validated)
    {

        $shareOrder = ShareFreeOrder::where($validated)->first();

        if(blank($shareOrder)){
            $shareGoods = ShareFreeGood::whereKey($validated['share_id'])->first(['goods_name', 'goods_id','goods_image', 'amount', 'numbers', 'days'])->toArray();
            $shareGoods['end_time'] = date('Y-m-d H:i:s', time() + ($shareGoods['days'] * 60 * 60 * 24) );

            $validated['now_numbers'] = 0; //兼容小程序端首页创建订单拉取不到数据

            $shareOrder = ShareFreeOrder::create(array_merge($validated, $shareGoods));
        }

        return $shareOrder;
    }


    /**
     * @param $order_id
     * @return ShareFreeOrder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getShareOrderDetail($order_id)
    {
        return ShareFreeOrder::whereKey($order_id)->first();
    }

    /**
     * 分享记录
     * @param $order_id
     * @return \Illuminate\Support\Collection
     */
    public function getShareLog($order_id)
    {
        return ShareFreeLog::where('order_id', $order_id)->get(['id', 'share_id', 'order_id', 'uid', 'avatar', 'nick_name']);
    }

    /**
     * 分享记录计数
     * @param $order_id
     * @return int
     */
    public function getShareLogCount($order_id)
    {
        return ShareFreeLog::where('order_id', $order_id)->count();
    }



    /**
     * 查看分享记录是否存在
     * @param $validated
     * @return bool
     */
    public function checkShareLog($validated)
    {
        return ShareFreeLog::where($validated)->exists();
    }


    /**
     * 生成分享记录
     * @param $validated
     * @return ShareFreeLog|\Illuminate\Database\Eloquent\Model
     */
    public function setShareLog($validated)
    {
        return ShareFreeLog::create($validated);
    }


    /**
     * @param $order_id
     * @param array $validated
     * @return bool|int
     */
    public function updateShareOrder($order_id, $validated = [])
    {
        return ShareFreeOrder::whereKey($order_id)->update($validated);
    }


    /**
     * @param $order_id
     * @return int
     */
    public function incShareCount($order_id)
    {
        //todo 后期并发 此处要加上mysql行锁
        return ShareFreeOrder::whereKey($order_id)->increment('now_numbers');
    }


}